//
//  JTTabBar.m
//  百思不得姐
//
//  Created by sun lei on 16/11/15.
//  Copyright © 2016年 BeiJingWangDianJieTong. All rights reserved.
//

#import "JTTabBar.h"

@interface JTTabBar ()

/** 中间的发布按钮 **/
@property (nonatomic, weak) UIButton *publishButton;

@end

@implementation JTTabBar

#pragma mark - 懒加载
/** 发布按钮 **/
- (UIButton *)publishButton {
    
    if (!_publishButton) {
        
        /**** 增加一个发布按钮 ****/
        UIButton *publishButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [publishButton setImage:[UIImage imageNamed:@"tabBar_publish_icon"] forState:UIControlStateNormal];
        [publishButton setImage:[UIImage imageNamed:@"tabBar_publish_click_icon"] forState:UIControlStateHighlighted];
        [publishButton addTarget:self action:@selector(publishClick:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:publishButton];
        _publishButton = publishButton;
    }
    
    return _publishButton;
}

#pragma mark - 初始化
- (instancetype)initWithFrame:(CGRect)frame {
    
    if (self = [super initWithFrame:frame]) {
        
        [self setBackgroundImage:[UIImage imageNamed:@"tabbar-light"]];
    }
    
    return self;
}

/**
 * 布局子控件
 */
- (void)layoutSubviews {
    
    [super layoutSubviews];
    
    /**** 按钮的尺寸 ****/
    CGFloat buttonWidth = self.jt_width / 5;
    CGFloat buttonHeight = self.jt_height;
    
    /**** 设置所有UITabBarButton的frame ****/
    CGFloat tabBarButtonY = 0;
    // 按钮索引
    NSInteger tabBarButtonIndex = 0;
    
    for (UIView *subView in self.subviews) {
        
        // 过滤掉非UITabBarButton
        if (subView.class != NSClassFromString(@"UITabBarButton")) continue;
        
        // 设置frame
        CGFloat buttonX = tabBarButtonIndex * buttonWidth;
        if (tabBarButtonIndex >= 2) {
            
            buttonX += buttonWidth;
        }
        [subView setFrame:CGRectMake(buttonX, tabBarButtonY, buttonWidth, buttonHeight)];
        
        // 增加索引
        tabBarButtonIndex++;
        
        /*
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            
            UIControl *tabBarButton = (UIControl *)subView;
            [tabBarButton addTarget:self action:@selector(tabBarButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        });
         */
    }
    
    /**** 设置中间的发布按钮的frame ****/
    [self.publishButton setJt_width:buttonWidth];
    [self.publishButton setJt_height:buttonHeight];
    [self.publishButton setJt_centerX:self.frame.size.width * 0.5];
    [self.publishButton setJt_centerY:buttonHeight * 0.5];
}

#pragma mark - 监听
- (void)publishClick:(UIButton *)sender {
    
    JTLogFunc
}

/*
- (void)tabBarButtonClick:(UIControl *)sender {
    
    JTLogFunc
}
 */

@end
